from info import constants
from info.models import User, News, Category
from info.utils.common import user_login_data
from info.utils.response_code import RET
from . import index_blu
from flask import render_template, current_app, session, request, jsonify, g


@index_blu.route("/")
@user_login_data
def index():
    #显示用户是否登录的逻辑

    #右侧的新闻排行的逻辑
    news_list = None
    try:
        news_list = News.query.order_by(News.clicks.desc()).limit(constants.CLICK_RANK_MAX_NEWS)
    except Exception as e:
        current_app.logger.error(e)
    news_dict_li= []
    #遍历对象列表，将对象的字典添加到字典列表中
    for news in news_list if news_list else []:
        news_dict_li.append(news.to_basic_dict())

    #获取新闻分类数据
    categories = Category.query.all()
    print("categories:%s" % categories)
    print("-----")
    print(type(categories))
    print("-----")
    #定义列表保存分类数据
    categories_dicts = []
    #
    for category in categories:
        #拼接内容
        categories_dicts.append(category.to_dict())

    data = {"user_info":g.user.to_dict() if g.user else None,
            "news_dict_li":news_dict_li,
            "categories": categories_dicts
            }

    return render_template("news/index.html",data = data)

@index_blu.route("/favicon.ico")
def favicon():
    return current_app.send_static_file("news/favicon.ico")

@index_blu.route("/newslist")
def get_news_list():
    """
    获取指定分类的新闻列表
    1，获取参数
    2，校验参数
    3，查询数据
    4，返回数据
    :return:
    """
    # 1，获取参数、
    args_dict = request.args
    page = args_dict.get("p","1")
    per_page = args_dict.get("per_page",constants.HOME_PAGE_MAX_NEWS)
    category_id = args_dict.get("cid","1")

    # 2,校验参数
    try:
        page = int(page)
        per_page = int(per_page)
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.PARAMERR, errmsg="参数错误")


    # 3. 查询数据并分页
    filters = [News.status == 0]
    # 如果分类id不为0，那么添加分类id的过滤
    if category_id != "0":
        filters.append(News.category_id == category_id)

    filters = []
    #如果分类id不为1，那么添加分类的过滤
    if category_id != "1":
        filters.append(News.category_id ==category_id)
        print("category_id is### %s " % category_id)
        print("filter---> %s" % filters)
    try:
        paginate = News.query.filter(*filters).order_by(News.create_time.desc()).paginate(page,per_page,False)
        # 获取查询出来的数据
        items = paginate.items
        print("items ---> %s" % items)
        # 获取到总页数
        total_page = paginate.pages
        current_page = paginate.page
        print("total page---> %s" % total_page)
        print("current page---> %s" % current_page)

    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno= RET.DBERR,errmsg= "数据查询失败")

    news_li = []
    for news in items:
        news_li.append(news.to_basic_dict())

    # 4,返回数据
    return jsonify(errno=RET.OK,errmsg="OK",totalPage= total_page,currentPage=current_page,newsList = news_li,cid = category_id)















